<template>
  <div>
    <el-form :model="form" inline>

      <el-form-item label="请选择仓库:">
        <el-select v-model="form.warehouseId">
          <el-option :label="item.name" :value="item.id" v-for="item in NewHouseList" :key="item.id"
            @click='getWarehouseTypeList(item.id), form.warehouseAreaId = -1' />
        </el-select>
      </el-form-item>
      <el-form-item label="库位号:">
        <el-input v-model="form.name" clearable />
      </el-form-item>
      <el-form-item label="请选择货区:">
        <el-select v-model="form.warehouseAreaId">
          <el-option :label="item.name" :value="item.id" v-for="item in WarehouseTypeList" :key="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="是否停用:">
        <el-select v-model="form.isStop">
          <el-option label="否" :value="0" />
          <el-option label="是" :value="1" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit">查询</el-button>
        <el-button type="primary" @click="createNew">新建库位</el-button>
        <!-- <el-upload v-model:file-list="fileList" class="upload-demo" list-type="excle" :show-file-list="false"
          action="https://run.mocky.io/v3/9d059bf9-4660-45f2-925d-ce80ad6c4d15" multiple :on-preview="handlePreview"
          :on-remove="handleRemove" :before-remove="beforeRemove" :limit="3" :on-exceed="handleExceed">
          <el-button type="primary">Click to upload</el-button>
          <template #tip>
            <div class="el-upload__tip">
              jpg/png files with a size less than 500KB.
            </div>
          </template>
</el-upload> -->
        <el-upload style="margin:0px 0px 0px 40px;display: flex;" v-model:file-list="fileList" class="upload-demo"
          :multiple="false" :on-preview="handlePreview" :http-request="importFIles" :on-remove="handleRemove"
          :before-remove="beforeRemove" :limit="1" :on-exceed="handleExceed">
          <el-button type="primary">导入库位</el-button>
        </el-upload>
        <!-- <el-button type="primary" @click="updataKW">导入库位</el-button> -->
        <el-button @click="pingMoban">下载模板</el-button>
      </el-form-item>
    </el-form>
  </div>
  <div class="table">
    <el-table ref="multipleTableRef" :data="tableData" style="width: 100%" @selection-change="handleSelectionChange"
      border>
      <el-table-column type="selection" width="55" />
      <el-table-column label="所属仓库" width="180">
        <template #default="scope">{{ scope.row.warehouseName }}</template>
      </el-table-column>
      <el-table-column label="所在货区" width="180">
        <template #default="scope">{{ scope.row.warehouseAreaName }}</template>
      </el-table-column>
      <el-table-column label="库位号" width="180">
        <template #default="scope">{{ scope.row.name }}</template>
      </el-table-column>
      <el-table-column label="是否停用" width="180">
        <template #default="scope">{{ scope.row.isStop == 0 ? '否' : '是' }}</template>
      </el-table-column>
      <el-table-column width="120">
        <template #header>
          <span>货物余量</span>
          <el-icon @click="SortBtn">
            <Sort />
          </el-icon>
        </template>
        <template #default="scope">{{ scope.row.cargoMargin }}</template>
      </el-table-column>
      <!-- <el-table-column label="云仓商品ID" width="180">
        <template #default="scope">{{ scope.row.cloudGoodId }}</template>
      </el-table-column> -->
      <el-table-column label="创建时间" width="180">
        <template #default="scope">{{ scope.row.createTime }}</template>
      </el-table-column>
      <el-table-column label="操作">
        <template #default="scope">
          <el-button link type="primary" size="small" @click.prevent="setwarehouseLocationdetail(scope.row)">
            编辑
          </el-button>
          <el-button link type="primary" size="small" @click=" PrintExpressReceipt(scope.row)">
            打印库位条码
            <!-- v-print="printObj" -->
          </el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
  <div class="page">
    <el-pagination v-model:current-page="currentPage4" v-model:page-size="pageSize4" :page-sizes="[10, 50, 100]"
      layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
      @current-change="handleCurrentChange" />
  </div>
  <!-- 新建 -->
  <div>
    <el-dialog v-model="CreateDialogVisible" width="350">
      <span>
        <el-form :model="Createform" inline>

          <el-form-item label="所属仓库:" width="85">
            <el-select v-model="Createform.warehouseId" style="width: 120px;">
              <el-option :label="item.name" :value="item.id" v-for="item in houseList" :key="item.id"
                @click='getWarehouseTypeList(item.id), Createform.warehouseAreaId = ""' />
            </el-select>
          </el-form-item>
          <el-form-item label="所属区域:">
            <el-select v-model="Createform.warehouseAreaId" style="width: 120px;">
              <el-option :label="item.name" :value="item.id" v-for="item in NewWarehouseTypeList" :key="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item label="库位号：">
            <el-input v-model="names" type="textarea" placeholder="库位号，多个用回车隔开" />
          </el-form-item>
        </el-form>
      </span>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="sbmintCereate">
            保存
          </el-button>
          <el-button @click="CreateDialogVisible = false; Createform = {}, names = ''">取消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
  <!-- 编辑 -->
  <div>
    <el-dialog v-model="setDialogVisible" width="350">
      <span>
        <el-form :model="setform" inline>
          <el-form-item label="库位:" width="85">
            <el-input v-model="setform.name" clearable />
          </el-form-item>
          <el-form-item label="所在仓库:" width="85">
            <el-select v-model="setform.warehouseId" style="width: 120px;">
              <el-option :label="item.name" :value="item.id" v-for="item in houseList" :key="item.id"
                @click='getWarehouseTypeList(item.id), setform.warehouseAreaId = ""' />
            </el-select>
          </el-form-item>
          <el-form-item label="所在货区:">
            <el-select v-model="setform.warehouseAreaId" style="width: 120px;">
              <el-option :label="item.name" :value="item.id" v-for="item in NewWarehouseTypeList" :key="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item label="货物余量:" width="85">
            <el-input v-model="setform.cargoMargin" clearable />
          </el-form-item>
          <el-form-item label="支持最大存储量:" width="85">
            <el-input v-model="setform.storageMax" clearable />
          </el-form-item>
          <!-- <el-form-item label="商品编码:" width="85">
            <el-input v-model="setform.goodCode" clearable />
          </el-form-item> -->
          <el-form-item label="是否停用:">
            <div>
              <label>
                <input type="radio" :value="0" v-model="setform.isStop"> 否
              </label>
              <label>
                <input type="radio" :value="1" v-model="setform.isStop"> 是
              </label>
            </div>
          </el-form-item>
        </el-form>
      </span>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="sbmintSet">
            保存
          </el-button>
          <el-button @click="setDialogVisible = false">取消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>

  <!-- 需要给外层包裹元素ref，在点击打印阶段需要使用ref获取打印元素，需要指定id用于捆绑触发打印的按钮 -->
  <!-- <el-dialog v-model="outerVisible" width="300">
    <span> <img ref="printTest" id="printTest" /></span>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="outerVisible = false">cancel</el-button>
        <el-button type="primary" v-print="printObj">confirm</el-button>
      </div>
    </template>
  </el-dialog> -->
  <el-dialog v-model="errordialogVisible" width="700">
    <span>
      <el-table :data="errorTableData" stripe style="width: 100%">
        <el-table-column prop="rowNum" label="行数" width="180" />
        <el-table-column prop="rowInfo" label="错误原因" />
      </el-table>
    </span>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="errordialogVisible = false">关闭</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, onBeforeMount, onMounted, onBeforeUnmount } from 'vue'
import { getWarehouseDownList, getWarehouseAreaDownList, warehouseLocationprintCode, warehouseLocationlist, warehouseLocationcreate, warehouseLocationupdate, warehouseLocationdetail, sysPrintTemplateSetGetSysPrintTemplateSetDetail } from '@/api/index'
import { ElMessage } from 'element-plus'
import { useAlertsStore } from '@/store/index'
import axios from 'axios'
const store = useAlertsStore()
// import { useWebSocketStore } from '@/store/webSoket'
// const useWebSocket = useWebSocketStore()
// import JsBarcode from 'jsbarcode'
// do not use same name with ref
onMounted(() => {
  doConnect()
})
const form = ref({
  warehouseId: -1,
  warehouseAreaId: -1,
  name: '',
  isStop: 0,
  orders: [
    {
      column: 'cargo_margin',
      asc: false
    }
  ],
  pageSize: 10,
  pageNum: 1
})
const tableData = ref([])
// 排序
const SortBtn = () => {
  form.value.orders[0].asc = !form.value.orders[0].asc
  getList()
}
const onSubmit = () => {
  console.log('submit!')
  getList()
}
const getList = () => {
  warehouseLocationlist(form.value).then(res => {
    const { data: { data } } = res
    total.value = data.total
    tableData.value = data.list
  })
}
onBeforeMount(() => {
  wareHouse()
  getWarehouseTypeList(-1)
  getList()
})
// 分页
const currentPage4 = ref(1)
const pageSize4 = ref(10)
const total = ref(0)
const handleSizeChange = (val) => {
  console.log(`${val} items per page`)
  form.value.pageSize = val
  getList()
}
const handleCurrentChange = (val) => {
  console.log(`current page: ${val}`)
  form.value.pageNum = val
  getList()
}

// table
const multipleSelection = ref([])
const handleSelectionChange = (val) => {
  multipleSelection.value = val
}

// 仓库下拉
const houseList = ref([])
const NewHouseList = ref([])
const wareHouse = async () => {
  const house = await getWarehouseDownList()
  const { data: { data } } = house
  houseList.value = data
  NewHouseList.value = [...data]
  houseList.value.shift()
  console.log(houseList.value)
}
// 货区类型
const WarehouseTypeList = ref([])
const NewWarehouseTypeList = ref([])
const getWarehouseTypeList = (val) => {
  getWarehouseAreaDownList(val).then(res => {
    const { data: { data } } = res
    console.log('data')
    console.log(data)
    WarehouseTypeList.value = [...data]
    NewWarehouseTypeList.value = data
    NewWarehouseTypeList.value.shift()
  })
}

// 创建
const Createform = ref({})
const CreateDialogVisible = ref(false)
const names = ref('')
const sbmintCereate = () => {
  Createform.value.names = names.value.split('\n')
  warehouseLocationcreate(Createform.value).then(res => {
    getList()
    CreateDialogVisible.value = false
    ElMessage.success('操作成功')
  })
}
const createNew = () => {
  CreateDialogVisible.value = true
}
// 编辑
const setform = ref({})
const setDialogVisible = ref(false)
const setwarehouseLocationdetail = (row) => {
  warehouseLocationdetail({ id: row.id }).then(res => {
    const { data: { data } } = res
    setform.value = data
    setDialogVisible.value = true
  })
}
const sbmintSet = () => {
  warehouseLocationupdate(setform.value).then(res => {
    getList()
    setDialogVisible.value = false
    ElMessage.success('操作成功')
  })
}
// const tmplat = ref(null)
const datas = ref({})
const PrintExpressReceipt = (row) => {
  warehouseLocationprintCode({ id: row.id }).then(res => {
    const { data: { data } } = res
    // const times = +new Date()
    if (localStorage.getItem('PrinterSetListKW')) {
      sysPrintTemplateSetGetSysPrintTemplateSetDetail({ id: 2 }).then(res => {
        JSON.parse(res.data.data.labelJson).forEach(element => {
          if (element.isOr) {
            if (element.name === 'list3') {
              datas.value[element.name] = row.name
            }
            if (element.name === 'waybillCode') {
              datas.value[element.name] = data
            }
          }
        })
        // const { data: { data } } = res
        // tmplat.value = res.data.data
        const lists = JSON.parse(localStorage.getItem('PrinterSetListKW'))
        const val = { cmd: 'print', requestID: '123458976', version: '1.0', task: { taskID: (new Date().getTime() + ''), preview: false, printer: lists[0].PrinterList, notifyMode: 'allInOne', previewType: 'pdf', documents: [{ documentID: '0123456789', contents: [{ data: datas.value, templateURL: `http://47.96.159.1:18889/config/sysPrintTemplateSet/getPrintTemplateByOrderId?id=${2}&userName=${localStorage.getItem('system_name')}` }] }] } }
        store.socket.send(JSON.stringify(val))
      })
    } else {
      ElMessage.success('先设置打印机')
    }
  })
}
const doConnect = () => {
  console.log('d打开了不')
  store.socket = new WebSocket('ws://localhost:13528')
  // 打开Socket
  store.socket.onopen = function (event) {
    // 监听消息
    store.socket.onmessage = function (event) {
      console.log('Client notified socket has closed', event)
    }
    // 监听Socket的关闭
    store.socket.onclose = function (event) {
      console.log('Client notified socket has', event)
    }
  }
}
// 销毁
onBeforeUnmount(() => {
  console.log('销毁')
  store.destroyed()
})
const errordialogVisible = ref(false)
const errorTableData = ref([])
// 导入
const importFIles = (files) => {
  console.log('daorul')
  console.log(files)
  const dataForm = new FormData()
  dataForm.append('file', files.file)
  const token = localStorage.getItem('system_token')
  if (files.file.name.includes('.xlsx') || files.file.name.includes('.xls')) {
    axios({
      headers: {
        'Content-Type': 'multipart/form-data',
        Authorization: 'Bearer ' + token
      },
      url: 'http://47.96.159.1:18889/warehouse/warehouseLocation/imp',
      method: 'post',
      data: dataForm
    }).then(res => {
      console.log(res)
      if (res.data.code === 500) {
        ElMessage({
          showClose: true,
          message: res.data.message,
          type: 'error'
        })
      } else if (res.data.code === 200) {
        if (res.data.data.hasError > 0) {
          errorTableData.value = res.data.data.errVoList
          errordialogVisible.value = true
          // ElMessage.error(()[0].rowInfo)
        } else {
          ElMessage({
            showClose: true,
            message: res.data.data.message,
            type: 'success'
          })
        }
        onSubmit()
      } else {
        ElMessage({
          showClose: true,
          message: res.data.message
        })
      }
      console.log(res)
    })
  } else {
    ElMessage({
      showClose: true,
      message: '上传xlsx或者xls类型文件',
      type: 'error'
    })
  }
}
const pingMoban = () => {
  window.open(
    'http://47.96.159.1:18889/warehouse/warehouseLocation/down'
  )
}

</script>

<style lang='less' scoped>
/* 显示打印的图片 */
#printTest {
  display: block;
  /* 让图片的宽度铺满整个页面 */
  width: 100%;
  height: 20vh;
  /* 让高度自适应 */
  position: absolute;
  top: 0;
  left: 0;
}
</style>
